<template>
    <div class="common-page page-staff-corp-company-demands" v-loading.fullscreen="loading">
        <div class="common-page__head">
            <comp-paths class="route" :paths="['/staff/corp', '/staff/corp/companys', '/staff/corp/company?companyId=' + companyId]"></comp-paths>
            <div class="title" v-if="company">
                <div class="text">{{ company.name }}</div>
                <el-button type="plain" size="small" icon="el-icon-plus" @click="addDemand()" v-if="self">提交需求</el-button>
            </div>
            <div class="title" v-else></div>
        </div>
        <comp-tabs class="common-page__head" :tabs="['/staff/corp/company?companyId=' + companyId, '/staff/corp/company/orders?companyId=' + companyId, '/staff/corp/company/products?companyId=' + companyId, $route.fullPath, '/staff/corp/company/attendances?companyId=' + companyId]"></comp-tabs>
        <comp-company-demands class="common-page__body" ref="list" :companyId="companyId" category="type4" select link>
            <template #body="scope">
                <el-button type="danger" size="mini" @click.stop="setDemandStatus(scope.data)" v-if="self && scope.data.approved === 'yes' && scope.data.status !== 'finished'">已解决</el-button>
            </template>
        </comp-company-demands>
        <comp-dialog title="提交需求" ref="demand" @close="addDemand('end')">
            <el-form size="small" label-width="98px" style="margin-right: 20px" @submit.native.prevent v-if="demand">
                <el-form-item label="需求类型：" required>
                    <el-select v-model="demand.type" style="width: 360px" placeholder="请选择" @change="addDemand('validate')">
                        <el-option v-for="data in env.demandTypes" :key="data.id" :label="data.name" :value="data.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="需求标题：" required>
                    <el-input type="textarea" v-model="demand.title" style="width: 360px" placeholder="请输入" :maxlength="100" :rows="2" resize="none" :readonly="loading" @change="addDemand('validate')"></el-input>
                </el-form-item>
                <el-form-item label="需求内容：" required>
                    <el-input type="textarea" v-model="demand.content" style="width: 360px" placeholder="请输入" :maxlength="1000" :rows="10" resize="none" :readonly="loading" @change="addDemand('validate')"></el-input>
                </el-form-item>
                <el-form-item label="联系人：" required>
                    <el-input v-model="demand.contacts.name" style="width: 360px" placeholder="请输入" :maxlength="100" :readonly="loading" @change="addDemand('validate')"></el-input>
                </el-form-item>
                <el-form-item label="联系电话：" required>
                    <el-input v-model="demand.contacts.mobile" style="width: 360px" placeholder="请输入" :maxlength="100" :readonly="loading" @change="addDemand('validate')"></el-input>
                </el-form-item>
                <el-form-item label="需求附件：">
                    <div style="width: 360px">
                        <el-tag style="margin: 0 10px 10px 0" v-for="(file, index) in demand.files" :key="index" disable-transitions closable @close="addDemand('demand-file-delete', file)">{{ file.name }}</el-tag>
                    </div>
                    <el-button type="plain" icon="el-icon-plus" @click="addDemand('demand-file-upload', 'image')">选择图片</el-button>
                    <el-button type="plain" icon="el-icon-plus" @click="addDemand('demand-file-upload', 'document')">选择文档</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-check" @click="addDemand('submit')">提交</el-button>
                    <el-button type="plain" icon="el-icon-close" @click="addDemand('end')">放弃</el-button>
                </el-form-item>
            </el-form>
        </comp-dialog>
    </div>
</template>

<script>
    import mixin from "../mixin";
    import { string, int, selectFile, cache } from "../util";
    export default {
        name: "page-staff-corp-company-demands",
        title: "需求信息",
        nodes: ["/menu/staff-corp"],
        childs: [],
        mixins: [mixin],
        data: () => ({
            loading: false,
            companyId: "",
            company: null,
            demand: null,
            self: false,
        }),
        methods: {
            search() {
                if (this.loading) return;
                this.$nextTick(() => this.$refs.list.init());
            },
            addDemand(action, data) {
                if (this.loading) return;
                let company = this.company;
                let demand = this.demand;
                if (action === "start" || !action) {
                    this.demand = this.plugins.user.formatDemand();
                    this.demand.company.id = company.id;
                    this.addDemand("validate");
                    this.$refs.demand.init();
                } else if (action === "validate") {
                    let form = demand;
                    let error = "";
                    error = error || (form.type ? "" : "请先选择需求类型！");
                    form.title = string(form.title).trim();
                    error = error || (form.title ? "" : "请先输入需求标题！");
                    form.content = string(form.content).trim();
                    error = error || (form.content ? "" : "请先输入需求内容！");
                    form.contacts.name = string(form.contacts.name).trim();
                    error = error || (form.contacts.name ? "" : "请先输入联系人！");
                    form.contacts.mobile = string(form.contacts.mobile).trim();
                    error = error || (form.contacts.mobile ? "" : "请先输入联系电话！");
                    if (data) this.plugins.modal.toast(error, "error");
                    return !error;
                } else if (action === "demand-file-upload") {
                    let type = data;
                    let timer = null;
                    let progress = (event) => timer = clearTimeout(timer) || setTimeout(() => this.plugins.modal.toast("上传进度：" + event.percent + "%", "info"), 200);
                    let upload = (type, file) => {
                        this.loading = true;
                        this.plugins.user.uploadFile(file, type, progress).then((res) => {
                            this.loading = false;
                            if (res.code === 0) {
                                demand.files.push(res.data);
                                this.addDemand("validate");
                            } else {
                                this.plugins.modal.alert("上传失败", res.code + "：" + res.msg, "error");
                            }
                        });
                    };
                    if (type === "image") selectFile("image/*").then((file) => {
                        if (file.size > 5 * 1048576) this.plugins.modal.toast("图片过大，不能大于5MB哦！请重新选择。", "error");
                        else upload(type, file);
                    });
                    if (type === "document") selectFile(".xls,.xlsx,.doc,.docx,.pdf").then((file) => {
                        if (file.size > 10 * 1048576) this.plugins.modal.toast("文档过大，不能大于10MB哦！请重新选择。", "error");
                        else upload(type, file);
                    });
                } else if (action === "demand-file-delete") {
                    let file = data;
                    let index = demand.files.indexOf(file);
                    if (index > -1) demand.files.splice(index, 1);
                } else if (action === "submit") {
                    if (!this.addDemand("validate", true)) return;
                    this.loading = true;
                    this.plugins.user.addDemand(demand).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            this.plugins.modal.toast("提交成功！", "success");
                            this.addDemand("end");
                            this.search();
                        } else {
                            this.plugins.modal.alert("提交失败", res.code + "：" + res.msg, "error");
                        }
                    });
                } else if (action === "end") {
                    this.$refs.demand.close();
                }
            },
            setDemandStatus(demand) {
                if (this.loading) return;
                this.plugins.modal.alert("操作确认", "确定已经解决了吗？", "warning", ["确定已解决", "还没有"]).then((ok) => {
                    if (!ok) return;
                    this.loading = true;
                    this.plugins.user.setDemandStatus(demand, "finished").then((res) => {
                        this.loading = false;
                        if (res.code === -1) return;
                        if (res.code === 0) {
                            this.plugins.modal.toast("操作成功！", "success");
                            this.search();
                        } else {
                            this.plugins.modal.alert("操作失败：", res.code + "：" + res.msg, "error");
                        }
                    });
                });
            },
            destroy() {
                if (this.loading) return;
                return true;
            },
            init() {
                if (this.loading) return;
                let query = this.$route.query;
                let company = null;
                this.loading = true;
                this.companyId = query.companyId;
                this.company = cache(query.companyId);
                this.$root.$refs.navbar.init();
                this.plugins.user.call(async () => {
                    let res = await this.plugins.user.init();
                    if (res.code === 0) { }
                    return res;
                }, async () => {
                    if (this.access(this.$route.name)) return { code: 0 };
                    return this.env.xhrErrors.find((error) => error.code === 4);
                }, async () => {
                    let res = await this.plugins.user.getCompany(query.companyId);
                    if (res.code === 0) company = res.data;
                    return res;
                }).then((res) => {
                    this.loading = false;
                    this.$root.$refs.navbar.init();
                    if (res.code === 0) {
                        this.company = cache(query.companyId, company);
                        this.self = this.company.employees.some((employee) => employee.client.id === this.profile.id);
                        this.search();
                    } else if (res.code === 2) {
                        this.$root.$refs.navbar.login();
                    } else {
                        this.plugins.modal.alert("页面加载失败", res.code + "：" + res.msg, "error").then(() => this.$router.replace("/staff/corp/companys"));
                    }
                });
            },
        },
    };
</script>

<style lang="scss">
    .page-staff-corp-company-demands {
        overflow: hidden;
    }
</style>